package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"stock-in-master/cache"
	"stock-in-master/model"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	var stock []model.Stock
	offset := (page - 1) * size
	reids_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, reids_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Order("stock_code DESC").Find(&stock)
		jsonData, _ := json.Marshal(&stock)
		cache.Rdb.Set(cache.Ctx, reids_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &stock)
	}
	var total int64
	model.DB.Model(&stock).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  stock,
		"total": total,
	})
}
